var service = new EbeimService();
$(window).load(function() {
	$("#dsType").change(function() {
		var dsType = $("#dsType").val();
		if (dsType == 1) {
			$(".db-config").fadeIn();
			$(".ds-path").css("display", "none");
		} else {
			$(".ds-path").fadeIn();
			$(".db-config").css("display", "none");
		}
	});
});

$('#datetimepicker').datetimepicker({
	step : 5
});
$('#datetimepicker').attr("value", formatDate(new Date()));
$('#spinner').spinner({
	min : 1,
	max : 100,
	step : 1
});
var setting = {
	check : {
		enable : false
	},
	data : {
		simpleData : {
			enable : true
		}
	},
	view : {
		expandSpeed : "",
		dblClickExpand : false,
		showLine : false
	},
	callback : {
		/* onClick: zTreeOnClick */
		onClick : onClick
	}
};
var zNodes = [ {
	name : "ROOT",
	open : true,
	isParent : true
} ];
/* var zTree = $.fn.zTree.getZTreeObj("tree"); */
/* var zTree; */
$(function() {
	zTree = $.fn.zTree.init($("#tree"), setting, zNodes);// 初始化zTree树
});

function onClick(e, treeId, treeNode) {
	currentTreeNode = treeNode;
	var path = getPath(treeNode);
	if (currentTreeNode.children != undefined) {
		return;
	}
	var service = new EbeimService();
	service.getSystemFiles(path, treeCallback);
	$(".curSelectedNode").click(function() {
		var noline = $(this).prev("span");
		var treeChild = $(this).next("ul");
		if (noline.hasClass("noline_open")) {
			noline.removeClass("noline_open").addClass("noline_close");
			treeChild.slideUp();
		} else {
			noline.removeClass("noline_close").addClass("noline_open");
			treeChild.slideDown();
		}
	})

}

function getPath(treeNode) {
	if (treeNode.getParentNode() == undefined) {
		return "";
	}
	var path = getPath(treeNode.getParentNode());
	if (path == "") {
		return treeNode.name;
	} else {
		return path + "/" + treeNode.name;
	}
}
function treeCallback(data) {
	// alert(data);
	// treeNode.children = data;
	var json = eval("(" + data + ")");
	zTree.addNodes(currentTreeNode, json, false);

}

function setDataSourcePath() {
	var path = "";
	var nodes = zTree.getSelectedNodes();

	if (nodes.length > 0) {
		path = getPath(nodes[0]);
	}
	// alert(path);
	$('#dsPath').attr("value", path);
}

var selectDataSource = function() {
	new PopupLayer({
		trigger : "#selectDataSource",
		popupBlk : '#blk1',
		closeBtn : "close1"
	});
};

var callback = function(data) {
	$("#save").removeAttr("disabled");
	var json = eval("(" + data + ")");
	if (json.code == 200 || json.code == "200") {
		alert("成功新增数据源！");
		self.location = document.referrer;
	} else {
		dsSecurityRankCheck(json.code,json.message);
	}
};

function setDynamicCode() {
	var dynamicCode = $("#dynamicCode").val();
	if (dynamicCode == "") {
		alert("动态验证码不能为空!");
		return;
	}
	saveDataSource(dynamicCode);
}

var saveDataSource = function(dynamicCode) {
	
	if ($('#dsName').val() == "") {
		alert("数据源名称不能为空");
		return;
	}
	if ($('#dsType').val() == "0") {
		if ($('#dsPath').val() == "") {
			alert("数据源路径不能为空");
			return;
		}
	}
	var isOpenLocalBackup = 0;
	if ($('#isOpenLocalBackup')[0].checked) {
		isOpenLocalBackup = 1;
	}
	
	var dsNeedKey = 0;
	var dsNeedKeyCked = $("#dsNeedKey")[0].checked;
	if(dsNeedKeyCked){
		dsNeedKey = 1;
	}
	var dsNeedCode = 0;
	var dsNeedCodeCked = $("#dsNeedCode")[0].checked;
	if(dsNeedCodeCked){
		dsNeedCode = 1;
	}
	var dsSecurityRank = 0;
	if(dsNeedKey==1 && dsNeedCode==0){
		dsSecurityRank = 1;
	}else if(dsNeedKey==0 && dsNeedCode==1){
		dsSecurityRank = 2;
	}else if(dsNeedKey==1 && dsNeedCode==1){
		dsSecurityRank = 3;
	}
	var ds = {
		name : $('#dsName').val(),
		description : $('#description').val(),
		dsType : $('#dsType').val(),
		isOpenLocalBackup : isOpenLocalBackup,
		dsSecurityRank : dsSecurityRank,
		dynamicCode : dynamicCode
	};
	var time = $('#datetimepicker').val();
	var stamp = new Date(time).getTime();
	var period = $("#period").val();
	var reg = /^[0-9]*[1-9][0-9]*$/.test(period); //正整数
	if(!reg){
		alert("时间间隔请输入正整数！");
		return;
	}
	var bs = {
		type : 1,
		backupTime : stamp,
		backupCycle : period,
		backupPeriod : $("#unit").val(),
	}
	var isEncrypt = 0;
	var isEncryptCked = $("#isEncrypt")[0].checked;
	if(isEncryptCked){
		isEncrypt = 1;
	}
	var config = {
		isEncrypt:isEncrypt,
		root : $('#dsPath').val(),
		scanType : $('#scanType').val(),
		scanHideFile : getCheckedValue($('#idScanHideFile')),
		recordCanNotReadFileInfo : getCheckedValue($('#idRecordCanNotReadFile')),
		recordEmptyDirectory : getCheckedValue($('#idRecordEmptyDirectory')),
		recordEmptyFile : getCheckedValue($('#idRecordEmptyFile')),
		verifyCompleteName : getCheckedValue($('#idVerifyCompleteName')),
		dbUsername : $("#dbUsername").val(),
		dbPassword : $("#dbPassword").val(),
		dbHost : $("#dbHost").val(),
		dbType : $("#dbType").val(),
		dbPort : $("#dbPort").val(),
		dbName : $("#dbName").val()
	}
	var json = {};
	json["datasource"] = ds;
	json["datasourceConfig"] = config;
	json["backStrategy"] = bs;
	// alert($('#idScanHideFile').prop('checked'));
	$("#save").attr("disabled","disabeld");
	service.addDataSource(json, callback);
};

var getCheckedValue = function(chk) {
	if (chk.prop("checked")) {
		return 1;
	}
	return 0;
};
/* 自定义checkbox样式 */
$(function() {
	$('.j-checkbox').iCheck({
		checkboxClass : 'icheckbox_square-blue',
		increaseArea : '20%'
	});
})

function confirmDsDir(){
	var abDir = $("#ab-ds-dir").html();
	if(abDir==""){
		$("#tips .dialogContentDiv").html("请选择目录");
		showDialog("tips",2000);
		return;
	}
	$("#h_ds_path").val(abDir);
	$("#ab-ds-dir").html("");
	$(".window").css("display","none");
	var ls = abDir.substring(abDir.length,abDir.length-1);
	if(ls == "/"){
		abDir = abDir.substring(0,abDir.length-1);
	}
	var h_which_path = $("#h_which_path").val();
	if(h_which_path == "dsPath"){
		$("#dsPath").val(abDir);
	}
	
}
function cancelDsDir(){
	$("#ab-ds-dir").html("");
	$(".window").css("display","none");
}

function selectDsPath(path,whichPath){
	
	if(whichPath){
		$("#h_which_path").val(whichPath);
	}
	
	var $W = $(window).width();
	var $H = $(window).height();
	var w = $(".window").width(); 
	var h = $(".window").height();
	$(".window").css("top",(($H-h)/2)-80);
	$(".window").css("left",($W-w)/2);
	$("#dsWindow").css("display","block");
	var abDir = $("#ab-ds-dir").html();
	if(abDir!=""){
		$("#ab-ds-dir").html(abDir+"\\"+path);
		service.getSystemDirs(abDir+"\\"+path, selectDsPathCB);
	}else{
		$("#ab-ds-dir").html(path);
		service.getSystemDirs(path, selectDsPathCB);
	}
}
function selectDsParentPath(path){
	var abDir = $("#ab-ds-dir").html();
	var idx = abDir.lastIndexOf("\\");
	if(idx!=-1){
		abDir = abDir.substring(0,idx);
		$("#ab-ds-dir").html(abDir);
    	service.getSystemDirs(abDir, selectDsPathCB);
	}else{
		$("#ab-ds-dir").html("");
		service.getSystemDirs("", selectDsPathCB);
	}
}
var selectDsPathCB = function(data){
	var json = eval("("+data+")");
	var content = "";
	for (var i = 0; i < json.length; i++) {
		var name = json[i].name;
		if(i==0){
			 var name = name.split("\\").join("\\\\");
		}
		content = content +
		"<li><a href='javascript:selectDsPath(\""+name+"/\")'>"+name+"</a></li>";
	}
	$(".w-dir-list ul").html(content);
}